package cn.edu.nbpt.campus_api.service.campus.impl;

import cn.edu.nbpt.campus_api.exception.BizException;
import cn.edu.nbpt.campus_api.mapper.campus.ClassMapper;
import cn.edu.nbpt.campus_api.mapper.campus.StudentMapper;
import cn.edu.nbpt.campus_api.model.ErrorCode;
import cn.edu.nbpt.campus_api.model.Page;
import cn.edu.nbpt.campus_api.model.campus.entity.Student;
import cn.edu.nbpt.campus_api.service.campus.StudentService;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private ClassMapper classMapper;


    @Override
    public Page<Student> selectStudentList(String name, String username, Integer gender, Date birthdayStartTime, Date birthdayEndTime, Date entryStartTime, Date entryEndTime, Date graduationStartTime, Date graduationEndTime, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Student> students = studentMapper.selectStudentList(name, username, gender, birthdayStartTime, birthdayEndTime, entryStartTime, entryEndTime, graduationStartTime, graduationEndTime);
        return Page.page(students);
    }

    @Override
    public Student selectStudent(Integer id) {
        Student student = studentMapper.selectStudent(id);
        if (student == null) throw new BizException(ErrorCode.SELECT_ERROR);
        return student;
    }

    @Override
    public Integer insertStudent(Student student) {
        student.setCreateBy("admin");
        student.setCreateTime(new Date());
        Integer row = studentMapper.insertStudent(student);
        if (row == 0)
            throw new BizException(ErrorCode.INSERT_ERROR);
        return student.getId();
    }

    @Override
    public Integer updateStudent(Student student) {
        student.setUpdateBy("user");
        student.setUpdateTime(new Date());
        Integer classId = student.getClassId();
        if (classMapper.selectClass(classId) == null)
            throw new BizException(ErrorCode.UPDATE_ERROR);
        return studentMapper.updateStudent(student);
    }

    @Override
    public Integer deleteStudent(List<Integer> ids) {
        Integer rows = studentMapper.deleteStudent(ids);
        if (rows == 0) throw new BizException(ErrorCode.DELETE_ERROR);
        return rows;
    }
}
